<?php

class Public_Post_WriteAction extends BlogPublicBaseAction
{
    /**
     * HTTP GET request handler
     *
     * @param AgaviRequestDataHolder $rd
     * @return mixed Target view
     */
    public function executeRead(AgaviRequestDataHolder $rd)
    {
        return 'Input';
    }
    
    /**
     * Process HTTP POST request
     *
     * @param AgaviRequestDataHolder $rd
     * @return mixed Target view
	 */
    public function executeWrite(AgaviRequestDataHolder $rd)
    {
        $params = $rd->getParameters();
        /* @var $model Public_PostsModel */
        $model = $this->getContext()->getModel('Posts', 'Public');
        $tm = $this->getContext()->getTranslationManager();
		$vm = $this->container->getValidationManager();
        
        $date = new DateTime($params['post_date']);
        $tags = preg_split('/\s*,\s*/', $params['tags']);
        $comments_allowed = isset($params['comments_allowed']);
        $published = isset($params['published']);
        
        // try to find post with the same shortcut
        $dup = $model->getPost(null, $params['post_shortcut']);
        if ($dup instanceof Post) {
            $vm->setError('post_shortcut', 'Post with the same shortcut already exists');
            return 'Error';
        }
        
        try {
            $post = $model->addPost($params['subject'], $params['post_shortcut'], $date, $params['body'], 
                $tags, $comments_allowed, $published);
        } catch (PropelException $e) {
            $vm->setError('general', 'Propel error. See logs for details.');
            return 'Error';
        }
        
        AgaviExecutionFilter::clearCache(array('posts_list'));
        $this->setAttribute('post', $post);
        return 'Success';
    }
    
	/**
	 * Returns the default view if the action does not serve the request
	 * method used.
	 *
	 * @return     mixed <ul>
	 *                     <li>A string containing the view name associated
	 *                     with this action; or</li>
	 *                     <li>An array with two indices: the parent module
	 *                     of the view to be executed and the view to be
	 *                     executed.</li>
	 *                   </ul>
	 */
	public function getDefaultViewName()
	{
		return 'Success';
	}

	public function isSecure()
    {
        return true;
    }
    
    public function getCredentials()
    {
        return array('posts.write');
    }
}

?>